import os
import docx
from flask import request

from app.libs.error_code import ParameterError, SuccessLike
from app.libs.redprint import Redprint
from config import AllOWED_FILENAME, FILE_PATH, URL


file_api = Redprint('file')


@file_api.route('/file_upload')
def file_upload():
    file = request.files['file']
    filename = file.filename
    if file and allowed_file(filename):
        save_path = FILE_PATH + filename
        file.save(save_path)
        r = dispose_file(save_path)
        os.remove(save_path)
        return SuccessLike(msg=r)
    else:
        return ParameterError(msg='文件不能为空,且后缀名必须是doc')


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in AllOWED_FILENAME


def dispose_file(save_path):
    document = docx.Document(save_path)
    table = document.tables[0]
    txt = ''

    # 处理表格数据
    for i in range(0, len(table.rows)):
        if table.cell(i, 0).text == '标题' or table.cell(i, 0).text == '文件名称':
            txt_title = table.cell(i, 1).text or '无名称'
        raw = table.cell(i, 0).text + " " + table.cell(i, 1).text + '\r\n'
        txt += raw
    table._element.getparent().remove(table._element)

    # 创建路径
    new_path = FILE_PATH + txt_title
    docx_path = new_path + '/' + txt_title + '.docx'
    txt_path = new_path + '/' + txt_title + '.txt'

    # 文件重复直接返回链接
    file_list = os.listdir(FILE_PATH)
    if txt_title in file_list:
        return download_path(txt_title)

    # 保存文件
    os.mkdir(new_path)
    document.save(docx_path)
    with open(txt_path, 'w') as f:
        f.write(txt)

    return download_path(txt_title)


def download_path(txt_title):
    temp = []
    paths = os.listdir(FILE_PATH + txt_title + '/')
    txt = txt_title + '.txt'
    docx = txt_title + '.docx'
    if txt not in paths or docx not in paths:
        return '文件不存在'

    txt_url = URL + txt_title + '/' + txt_title + '.txt'
    docx_url = URL + txt_title + '/' + txt_title + '.docx'
    temp.append(txt_url)
    temp.append(docx_url)
    return temp
